package com.changgou.seckill.mq.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.service.SeckillOrderService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RabbitListener(queues = "${mq.seckillpay.seckillpayqueue}")
public class SeckillPayMessageListener {
    @Autowired
    private SeckillOrderService seckillOrderService;

    @RabbitHandler
    public void getMessage(String message) {
        System.out.println(message);
        //将支付信息转成map
        try {
            //将支付信息转成Map
            Map<String, String> resultMap = JSON.parseObject(message, Map.class);
            //return_ code-> 通信标识- SUCCESS
            String return_code = resultMap.get("return_code");
            String out_trade_no = resultMap.get("out_trade_no");
            String attach = resultMap.get("attach");
            Map<String, String> attachMap = JSON.parseObject(attach, Map.class);
            if (return_code.equals("SUCCESS")) {
                String result_code = resultMap.get("result_code");
                if (result_code.equals("SUCCESS")) {
                    seckillOrderService.updateOrder(attachMap.get("username"), resultMap.get("transaction_id"), resultMap.get("time_end"));
                } else {
                    seckillOrderService.deleteOrder(attachMap.get("username"));
                }
            }
            //result_ code->业务结果-SUCCESS->该订单状态
            //FAIL -> 删除订单[真实工作中存入到NySQL.]->回滚库存
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
